package com.bears.god.sup.servlet.operation;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.Income;
import com.bears.god.sup.service.IncomeService;
import com.bears.god.sup.service.ServiceDAOFactory;

@WebServlet("/edit")
public class EditIncomeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6L;
	public static final String METHOD_EDIT = "0";
	public static final String METHOD_FINISH = "1";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String method = req.getParameter("method");

		if (method != null) {
			switch (method) {
			case EditIncomeServlet.METHOD_EDIT:
				edit(req, resp);
				break;
			case EditIncomeServlet.METHOD_FINISH:
				finish(req, resp);
				break;
			}

		}

	}

	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		Income Editincome = new Income();
		try {

			int id = Integer.parseInt(req.getParameter("id"));
			Editincome.setId(id);
			IncomeService service = ServiceDAOFactory.getIncomeDAO();

			String daily = req.getParameter("daily");

			Editincome.setDailyIncome(Double.parseDouble(daily));

			// 得到long类型当前时间
			long l = System.currentTimeMillis();
			// new日期对象
			Date date = new Date(l);
			// 转换提日期输出格式
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String lastTime = dateFormat.format(date);
			Editincome.setLastDate(lastTime);
			service.update(Editincome);
			req.setAttribute("EditIncome_err", "修改成功");
			req.getRequestDispatcher("/Income?id="+(id/5+1)).forward(req, resp);

		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("EditIncome_err", "修改失败");
			try {
				req.getRequestDispatcher("WEB-INF/view/manager/editincome.jsp").forward(req, resp);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	private void edit(HttpServletRequest req, HttpServletResponse resp) {

		int id = Integer.parseInt(req.getParameter("id"));
		Income income = null;

		try {
			IncomeService service = ServiceDAOFactory.getIncomeDAO();
			income = service.findById(id);
			req.setAttribute("income", income);
			req.getRequestDispatcher("WEB-INF/view/manager/editincome.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
